package com.zx.controller;

import com.zx.common.ResponseCode;
import com.zx.entity.User;
import com.zx.repository.UserRepository;
import com.zx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository repository;

    //查询用户列表
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "0") Integer page,
                             @RequestParam(value = "size", defaultValue = "9") Integer size,
                             Map<String,Object> map){
        PageRequest request = PageRequest.of(page, size);
        Page<User> user = userService.find(request);
        map.put("users", user);
        return new ModelAndView("user/list", map);
    }
    //删除用户
    @GetMapping("/delete/{userId}")
    public ModelAndView delete(@PathVariable("userId") Integer id,
                               Map<String,Object> map){
        User user = repository.getOne(id);
        repository.delete(user);
        map.put("msg",ResponseCode.DELETE_SUCCESS.getDesc());
        map.put("url","/foodshare/user/list");
        return new ModelAndView("common/success",map);
    }
    //修改用户信息
    @GetMapping("/list/{userId}")
    public ModelAndView EditUser(@PathVariable("userId") Integer id,
                                 Map<String,Object> map){
        User user = repository.getOne(id);
        map.put("user",user);
        return new ModelAndView("user/editUser",map);
    }
    @PostMapping("/saveUser")
    public ModelAndView saveUser(User user,
                                 Map<String,Object> map){
        repository.save(user);
        map.put("url","/foodshare/user/list");
        map.put("msg",ResponseCode.EDIT_SUCCESS.getDesc());
        return new ModelAndView("common/success");
    }
    //新增用户
    @GetMapping("/addUser")
    public ModelAndView addUser(){
        return new ModelAndView("user/addUser");
    }
    @PostMapping("/addUser")
    public ModelAndView addUser(@RequestParam("username") String Username,
                                    User user,
                                    Map<String,Object> map){
        User u  = userService.findUserInfoByUsername(Username);
        if(u!=null){
            map.put("msg",ResponseCode.USER_EXISTS.getDesc());
            map.put("url","/foodshare/user/addUser");
            return new ModelAndView("common/error");
        }
        repository.save(user);
        map.put("msg",ResponseCode.SIGNUP_SUCCESS.getDesc());
        map.put("url","/foodshare/user/list");
        return new ModelAndView("common/success");
    }
    //管理员登录界面
    @GetMapping("/login")
    public ModelAndView agent(){
        return new ModelAndView("agent/login");
    }
    //普通用户登录界面
    @GetMapping("/ordinary")
    public ModelAndView ordinary(){
        return new ModelAndView("user/login");
    }
    //普通用户登录验证
    @PostMapping("/checkin")
    @ResponseBody
    public ModelAndView checkin(@RequestParam("username") String Username,
                              @RequestParam("password") String Password,
                              Map<String,Object> map,HttpSession session){
        User user = userService.findUserInfoByUsername(Username);
        if(user==null){
            map.put("msg", ResponseCode.NEED_SIGNUP.getDesc());
            return new ModelAndView("user/login");
        }
        if (!StringUtils.isEmpty(Username)&&Password.equals(user.getPassword())) {
            session.setAttribute("loginUser",Username);
            return new ModelAndView(new RedirectView("/foodshare/main/index"));
        }
        session.invalidate();
        map.put("msg",ResponseCode.LOGIN_FAIL.getDesc());
        return new ModelAndView("user/login");
    }
    //管理员登录验证
    @PostMapping("/agentCheckin")
    public ModelAndView agentCheckin(@RequestParam("username") String Username,
                                     @RequestParam("password") String Password,
                                     Map<String,Object> map,HttpSession session){
        User user = userService.findUserInfoByUsername(Username);
        if(user==null){
            map.put("msg",ResponseCode.NEED_SIGNUP.getDesc());
            return new ModelAndView("agent/login");
        }
        else if(!user.getRole().equals(0)){
            map.put("msg",ResponseCode.ROLE_ERROR.getDesc());
            return new ModelAndView("user/login");
        }
        else if (!StringUtils.isEmpty(Username)&&Password.equals(user.getPassword())) {
            session.setAttribute("loginUser",Username);
            return new ModelAndView(new RedirectView("/foodshare/back/index"));
        }
        session.invalidate();
        map.put("msg",ResponseCode.LOGIN_FAIL.getDesc());
        return new ModelAndView("agent/login");
    }
    //用户注册界面
    @GetMapping("/signUp")
    public ModelAndView signUp(){return new ModelAndView("user/SignUp");}
    //用户注册验证
    @PostMapping("/signUpCheck")
    public ModelAndView signUpCheck(@RequestParam("username") String Username,
                                    User user,
    Map<String,Object> map){
        User u  = userService.findUserInfoByUsername(Username);
        if(u!=null){
            map.put("msg",ResponseCode.USER_EXISTS.getDesc());
            map.put("url","/foodshare/user/signUp");
            return new ModelAndView("common/error");
        }
        repository.save(user);
        map.put("msg",ResponseCode.SIGNUP_SUCCESS.getDesc());
        map.put("url","/foodshare/user/login");
        return new ModelAndView("common/success");
    }
    //忘记密码
    @GetMapping("/forget")
    public String forget(){
        return "user/forget";
    }
    @PostMapping("/forgetCheck")
    public ModelAndView forgetCheck(User user,
                               Map<String,Object> map){
        User check = userService.findUserInfoByUsername(user.getUsername());
        if(check.getQuestion().equals(user.getQuestion())&&check.getAnswer().equals(user.getAnswer())){
            check.setPassword(user.getPassword());
            repository.save(check);
            if(check.getRole().equals(0)){
                map.put("url","/foodshare/user/login");
            }else{
                map.put("url","/foodshare/user/ordinary");
            }
            map.put("msg",ResponseCode.EDIT_SUCCESS.getDesc());
            return new ModelAndView("common/success");
        }
        map.put("msg",ResponseCode.ERROR.getDesc());
        map.put("url","foodshare/main/index");
        return new ModelAndView("common/error");
    }
    //后台登出
    @GetMapping("/logout")
    public ModelAndView logout(Map<String,Object> map){
        map.put("url","/foodshare/user/login");
        map.put("msg",ResponseCode.LOGOUT_SUCCESS.getDesc());
        return new ModelAndView("common/success",map);
    }
}